<?php
/**
 * http Request Base
 */

namespace dragon\Request\Base;

use dragon\Contract\Request;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class HttpRequest extends Client
{
    public function run(Request $request, $options = []) {
        $method = strtoupper($request->getMethod());
        try {
            $params = [];
            if(!$method) $method = 'GET';

            if($method == 'GET') {
                $params['query'] = $request->getGet() ?: $request->getParams();
            } elseif ($method == 'POST') {
                $params['form_params'] = $request->getPost() ?: $request->getParams();
            }

            $response = $this->request($method, $request->getUrl(), array_merge($params, $options));

            $request->setStatusCode($response->getStatusCode());
            $request->setResponse($response->getBody()->getContents());
        } catch (RequestException $e) {
            $message = '网络请求异常';
            if ($e->hasResponse()) {
                $message .= ': '.$e->getResponse();
            }
            $request->setStatusCode($e->getCode());
            $request->setMessage($message);
        }

        return $request;
    }
}